package cn.xiaolang.thread.queue;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * SynchronousQueue入门
 * <p>
 * 使用SynchronousQueue的目的就是保证
 * “对于提交的任务，如果有空闲线程，则使用空闲线程来处理；否则新建一个线程来处理任务”
 * </p>
 *
 * @author fuhw/Dean
 * @date 2020-03-17
 */
@Slf4j
public class SynchronousQueueStarted {
    /**
     * 插入数据的线程和获取数据的线程，交替执行
     */
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue = new LinkedBlockingDeque();
        new Thread(new QueueProducer(blockingQueue), "p1").start();
        new Thread(new QueueConsumer(blockingQueue), "c1").start();
        new Thread(new QueueConsumer(blockingQueue), "c2").start();
    }

    static class QueueProducer implements Runnable {


        private BlockingQueue blockingQueue;
        private AtomicInteger counter = new AtomicInteger(0);

        public QueueProducer(BlockingQueue blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    int countNo = counter.incrementAndGet();
                    log.info("put:{}", countNo);
                    blockingQueue.put(countNo);
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class QueueConsumer implements Runnable {

        private BlockingQueue blockingQueue;

        public QueueConsumer(BlockingQueue blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Object take = blockingQueue.take();
                    log.info("take:{}", take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}




